<!-- src/views/Users.vue -->
<template>
  <div>
    <el-container>
      <el-header>
        <div class="header-content">
          <h2>用户管理</h2>
          <div>
            <el-button type="primary" @click="showAddUserModal">
              <i class="bi bi-plus-lg"></i> 添加用户
            </el-button>
            <el-button type="primary" @click="handleBack">
              <i class="bi bi-arrow-left"></i> 返回
            </el-button>
          </div>
        </div>
      </el-header>
      <el-main>
        <el-card shadow="hover">
          <!-- 加载指示器 -->
          <el-spin :loading="loading" tip="加载中...">
            <!-- 用户列表 -->
            <el-table
              v-if="users.length > 0"
              :data="paginatedUsers"
              style="width: 100%"
              stripe
            >
              <el-table-column prop="id" label="ID" width="50"></el-table-column>
              <el-table-column prop="username" label="用户名"></el-table-column>
              <el-table-column prop="role" label="角色"></el-table-column>
              <el-table-column prop="created_at" label="创建时间"></el-table-column>
              <el-table-column label="操作" width="200">
                <template #default="{ row }">
                  <div class="button-group">
                    <el-button size="mini" type="primary" @click="showEditUserModal(row)">
                      <i class="bi bi-pencil-square"></i> 编辑
                    </el-button>
                    <el-button size="mini" type="danger" @click="deleteUser(row.id)">
                      <i class="bi bi-trash-fill"></i> 删除
                    </el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
            <!-- 无数据提示 -->
            <div v-else class="no-data">
              <el-empty description="暂无数据"></el-empty>
            </div>
          </el-spin>

          <!-- 分页组件 -->
          <div class="pagination-container" v-if="total > pageSize">
            <el-pagination
              background
              layout="prev, pager, next, jumper"
              :current-page="currentPage"
              :page-size="pageSize"
              :total="total"
              @current-change="handlePageChange"
            >
            </el-pagination>
          </div>
        </el-card>
      </el-main>
    </el-container>

    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      v-model="addUserVisible"
      width="50%"
      @close="resetNewUser"
      :teleported="false"
    >
      <el-form :model="newUser" label-width="80px">
        <el-form-item
          label="用户名"
          prop="username"
          :rules="[{ required: true, message: '请输入用户名', trigger: 'blur' }]"
        >
          <el-input v-model="newUser.username" placeholder="请输入用户名"></el-input>
        </el-form-item>

        <el-form-item
          label="密码"
          prop="password"
          :rules="[{ required: true, message: '请输入密码', trigger: 'blur' }]"
        >
          <el-input v-model="newUser.password" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>

        <el-form-item label="角色">
          <el-select v-model="newUser.role" placeholder="请选择">
            <el-option label="学生" value="student"></el-option>
            <el-option label="管理员" value="admin"></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="closeAddUserModal">取消</el-button>
        <el-button type="primary" @click="addUser">确定</el-button>
      </template>
    </el-dialog>

    <!-- 编辑用户对话框 -->
    <el-dialog
      title="编辑用户"
      v-model="editUserVisible"
      width="50%"
      @close="resetEditUser"
      :teleported="false"
    >
      <el-form :model="editUser" label-width="80px">
        <el-form-item
          label="用户名"
          prop="username"
          :rules="[{ required: true, message: '请输入用户名', trigger: 'blur' }]"
        >
          <el-input v-model="editUser.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <!-- 留空表示不修改密码 -->
          <el-input
            v-model="editUser.password"
            type="password"
            placeholder="留空表示不修改"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="editUser.role" placeholder="请选择">
            <el-option label="学生" value="student"></el-option>
            <el-option label="管理员" value="admin"></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="closeEditUserModal">取消</el-button>
        <el-button type="primary" @click="updateUser">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import { ref, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';

export default {
  name: 'Users',
  setup() {
    const router = useRouter();

    // 用户数据
    const users = ref([]);

    // 控制添加/编辑对话框的显示与否
    const addUserVisible = ref(false);
    const editUserVisible = ref(false);

    // 添加用户表单
    const newUser = ref({
      username: '',
      password: '',
      role: 'student',
    });

    // 编辑用户表单
    const editUser = ref({});

    // 分页相关
    const currentPage = ref(1);
    const pageSize = ref(10);
    const total = ref(0);

    // 加载状态
    const loading = ref(false);

    // 当前登录用户（用于识别谁在操作）
    // 从 localStorage 中读取，若没有就假设是admin
    const user = ref(
      JSON.parse(localStorage.getItem('user')) || { role: 'admin', username: 'admin', id: 1 }
    );

    /**
     * 获取用户列表
     */
    const fetchUsers = () => {
      loading.value = true;
      axios
        .get(`/api/users?page=${currentPage.value}&limit=${pageSize.value}`)
        .then((response) => {
          if (response.data.users && typeof response.data.total === 'number') {
            users.value = response.data.users;
            total.value = response.data.total;
          } else {
            ElMessage.error('获取用户列表失败，响应格式不正确');
          }
          loading.value = false;
        })
        .catch((error) => {
          console.error('获取用户列表失败:', error);
          ElMessage.error('获取用户列表失败');
          loading.value = false;
        });
    };

    /**
     * 点击“添加用户”按钮，显示对话框
     */
    const showAddUserModal = () => {
      addUserVisible.value = true;
    };

    /**
     * 点击“取消”时，关闭添加用户对话框
     */
    const closeAddUserModal = () => {
      addUserVisible.value = false;
      resetNewUser();
    };

    /**
     * 点击“确定”时，调用接口添加用户
     */
    const addUser = () => {
      // 基本校验
      if (!newUser.value.username || !newUser.value.password) {
        ElMessage.warning('请填写所有必填项');
        return;
      }

      console.log('添加用户数据:', newUser.value);

      axios
        .post('/api/users', {
          ...newUser.value,              // 表单里输入的用户名、密码、角色
          admin_username: user.value.username, // 当前登录用户，用于日志
        })
        .then((response) => {
          if (response.data.success) {
            ElMessage.success('添加用户成功');
            addUserVisible.value = false;
            fetchUsers(); // 重新获取用户列表
            resetNewUser();
          } else {
            ElMessage.error(response.data.message || '添加用户失败');
          }
        })
        .catch((error) => {
          console.error('添加用户失败:', error);
          ElMessage.error('添加用户失败');
        });
    };

    /**
     * 点击“编辑”按钮，显示编辑对话框
     */
    const showEditUserModal = (userData) => {
      // 复制一份用户数据，且清空密码
      editUser.value = { ...userData, password: '' };
      editUserVisible.value = true;
    };

    /**
     * 点击“取消”时，关闭编辑用户对话框
     */
    const closeEditUserModal = () => {
      editUserVisible.value = false;
      resetEditUser();
    };

    /**
     * 点击“确定”时，调用接口更新用户
     */
    const updateUser = () => {
      // 如果用户名空了，不能更新
      if (!editUser.value.username) {
        ElMessage.warning('请填写用户名');
        return;
      }

      console.log('更新用户数据:', editUser.value);

      // 如果密码为空，表示不修改密码 => 删除 password 字段
      const payload = { ...editUser.value };
      if (!payload.password) {
        delete payload.password;
      }

      // 给后端带上 admin_username 识别谁在操作
      axios
        .put(`/api/users/${editUser.value.id}`, {
          ...payload,
          admin_username: user.value.username,
        })
        .then((response) => {
          if (response.data.success) {
            ElMessage.success('更新用户成功');
            editUserVisible.value = false;
            fetchUsers();
          } else {
            ElMessage.error(response.data.message || '更新用户失败');
          }
        })
        .catch((error) => {
          console.error('更新用户失败:', error);
          ElMessage.error('更新用户失败');
        });
    };

    /**
     * 删除用户
     */
    const deleteUser = (id) => {
      ElMessageBox.confirm('确定删除这个用户吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          axios
            .delete(`/api/users/${id}`, {
              data: { username: user.value.username },
            })
            .then((response) => {
              if (response.data.success) {
                ElMessage.success('删除用户成功');
                fetchUsers();
              } else {
                ElMessage.error(response.data.message || '删除用户失败');
              }
            })
            .catch((error) => {
              console.error('删除用户失败:', error);
              ElMessage.error('删除用户失败');
            });
        })
        .catch(() => {
          // 用户取消删除
        });
    };

    /**
     * 返回仪表盘
     */
    const handleBack = () => {
      router.push('/dashboard');
    };

    /**
     * 分页切换
     */
    const handlePageChange = (page) => {
      currentPage.value = page;
      fetchUsers();
    };

    /**
     * 重置添加用户表单
     */
    const resetNewUser = () => {
      newUser.value = {
        username: '',
        password: '',
        role: 'student',
      };
    };

    /**
     * 重置编辑用户表单
     */
    const resetEditUser = () => {
      editUser.value = {};
    };

    /**
     * 页面挂载后获取用户
     */
    onMounted(() => {
      fetchUsers();
    });

    /**
     * 计算当前页显示的用户
     */
    const paginatedUsers = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value;
      const end = start + pageSize.value;
      return users.value.slice(start, end);
    });

    return {
      users,
      addUserVisible,
      editUserVisible,
      newUser,
      editUser,
      currentPage,
      pageSize,
      total,
      loading,
      user,

      showAddUserModal,
      closeAddUserModal,
      addUser,
      showEditUserModal,
      closeEditUserModal,
      updateUser,
      deleteUser,
      handleBack,
      handlePageChange,
      resetNewUser,
      resetEditUser,
      paginatedUsers,
    };
  },
};
</script>

<style scoped>
.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 60px;
  padding: 0 20px;
}

.el-header {
  background-color: #409eff;
  color: white;
}

.button-group {
  display: flex;
  gap: 5px;
  flex-wrap: nowrap;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.no-data {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}
</style>
